package com.kmdx.schedule;


import cn.hutool.crypto.SecureUtil;
import com.google.gson.Gson;
import com.kmdx.entity.SubmitRep;
import com.kmdx.entity.SubmitTempleReq;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import org.apache.commons.io.filefilter.FileFilterUtils;

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


import java.io.*;
import java.net.URI;
import java.util.Base64;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

@Component
@EnableScheduling
public class SendSmsSchedule {
    final Base64.Encoder encoder = Base64.getEncoder(); //base64
    private final static String uri = "http://112.35.1.155:1992/sms/tmpsubmit"; //短信請求接口
    private final static String filePath = "D:\\qzd"; //短信存放路徑
    Gson gson = new Gson();
    private Logger logger = LoggerFactory.getLogger(SendSmsSchedule.class);

    @Scheduled(cron = "0 0/1 * * * ?")
    public void querySmsFile() throws Exception {
        logger.info("开始发送短信-------------------");
        InputStream inputStream = null;
        Reader reader = null;
        Collection<File> files = null;
        List<InputStream> inputStreamList=null;
        List<Reader> readerList=null;
        try {
            inputStreamList=new LinkedList<>();
            readerList=new LinkedList<>();
            files = FileUtils.listFiles(new File(filePath), FileFilterUtils.fileFileFilter(), null);

            for (File file : files) {

                inputStream = new FileInputStream(file);
                reader = new InputStreamReader(inputStream, "UTF-8");
                inputStreamList.add(inputStream);
                readerList.add(reader);
                List<String> list = IOUtils.readLines(reader);

                for (String s : list) {

                    SubmitTempleReq templeReq = gson.fromJson(s, SubmitTempleReq.class);
                    senSms(templeReq);
                }

            }
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage());
            e.printStackTrace();
        } finally {
            for (InputStream input:inputStreamList){
                if (null!=input){
                    IOUtils.close(input);
                }
            }
            for (Reader re:readerList){
                if (null!=re){
                    IOUtils.close(re);
                }
            }
            // 一定先关闭流
            for (File file : files) {
                if (!file.delete()){
                    System.gc();//强制回收资源
                }
            }

        }

    }
    //开始发送短信
    private void senSms(SubmitTempleReq templeReq) throws Exception {


        CloseableHttpClient build = HttpClientBuilder.create().build();


        StringBuffer buffer = new StringBuffer();
        buffer.append(templeReq.getEcName());
        buffer.append(templeReq.getApId());
        buffer.append(templeReq.getSecretKey());
        buffer.append(templeReq.getTemplateId());
        buffer.append(templeReq.getMobiles());
        buffer.append(templeReq.getParams());
        buffer.append(templeReq.getSign());
        buffer.append(templeReq.getAddSerial());

        templeReq.setMac(SecureUtil.md5(buffer.toString()).toLowerCase());//mac 必須進行md5加密  全部轉化成小寫

        URI url = new URI(uri);
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(encoder.encodeToString(gson.toJson(templeReq).getBytes()), "utf-8");//通过base64加密
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        CloseableHttpResponse execute = build.execute(httpPost);
        if (execute.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
            SubmitRep rep = gson.fromJson(EntityUtils.toString(execute.getEntity()), SubmitRep.class);
            System.out.println(rep);
        }
        if (null != build) {
            build.close();
        }

    }

}
